<?php
	if(!isset($_SESSION)){
		session_start();
	}

	//Clear previous messages
	if(isset($_SESSION['error'])) unset($_SESSION['error']);
	if(isset($_SESSION['success'])) unset($_SESSION['success']);
	
	//Get values from the form
	$userName = $_SESSION['userName'];
	if($_SESSION['userTypeId'] <= 2){
		$userFullName = $_POST['userFullName'];
		$userAddress = $_POST['userAddress'];
		$userTelephone = $_POST['userTelephone'];
	}
	$currentPassword = $_POST['currentPassword']; 
	$newPassword = $_POST['newPassword']; 
	$confirmPassword = $_POST['confirmPassword']; 
	
	//Validate
	include('../dbConnection.php');
	if($_SESSION['userTypeId'] <= 2){
		if(mysql_query("UPDATE users SET userFullName = '$userFullName', userAddress = '$userAddress', userTelephone = '$userTelephone' WHERE userName='$userName'")){
			$_SESSION['success'] = 'Update Successfully ';
		}else{
			$_SESSION['error'] = 'Error Occured!';
		}
	}
	
	if($currentPassword != '' ){
		if($newPassword != '' & $confirmPassword != '' ){
			if($result = mysql_query("SELECT userPassword FROM users WHERE userName='$userName'")){
				$row = mysql_fetch_row($result);
					if($row[0] == md5($currentPassword)){
							if($newPassword == $confirmPassword){
								$changedPassword = md5($newPassword);
								if(mysql_query("UPDATE users SET userPassword = '$changedPassword' WHERE userName='$userName'")){
									$_SESSION['success'] = 'Update Successfully ';
								}else
									$_SESSION['error'] = 'Error Occured!';
							}else
								$_SESSION['error'] = 'Confirm password failed.';
					}else
						$_SESSION['error'] = 'Enter your current password correctly.';
			}else
				$_SESSION['error'] = 'Error Occured!';				
				
		}else
			$_SESSION['error'] = 'You have to fill both new and confirm password fields';
	}else
		$_SESSION['error'] = 'You should enter current password to change the password!';
	
	if ($currentPassword=='123456' && $newPassword != '' && $confirmPassword != ''){
		if(session_destroy()){
			header("Location: ../../");
		}
	}	
	else{
	$_SESSION['pages']='profile.php';
	header("location: ../../");	
	}
?>